package java101;

	import java.io.*;
	import java.util.*; 

	// Program to count recurring letters from input file including list of United States names

	public class LetterOccurenceCounter
	{
		static Scanner inFile;
		
		private static String getInputFileName(Scanner console)
		{
			System.out.print("Name of text file to parse:");
			return console.next();
		}
		private static void usage()
		{
			System.out.print("Usage:LetterOccurrenceCounter <input-file-name>");
		}
		
		public static void main (String[] args)
		{
			Scanner console = new Scanner (System.in);  // read user input
			inFile = null;  // read text from here
			File file = null;  // file handle
			// String instr inputFileName = null ... query this from the user
			String instr = "";
			Hashtable <Character, Integer> table = new Hashtable<Character, Integer>();  // table to hold parsed letters
			
			boolean done = false;
			
			
			
			//Query for a file
			while(!done)
			{
				String inFileName;
				inFileName = getInputFileName(console);
				file = new File(inFileName);
				try
				{
					inFile = new Scanner(file);
					done = true;
				}
				catch(IOException e)
				{
					System.out.println("Error opening input file " + inFileName);
					usage();
				}
			}
			// while there is input do
			while(inFile.hasNext());
			{  // get a character
				instr = inFile.next();
				System.out.println("Parsing: " + instr);
				//  if character is in a - z or A - Z then
				for(int idx=0; idx<instr.length(); idx++)
				{
					// use char as key into Hashtable and increment by 1
					char chr = instr.charAt(idx);
					// only add if a letter
					if(Character.isLetter(chr))
					{
						chr = Character.toLowerCase(chr);
						table.put(chr, table.containsKey(chr)?table.get(chr):0+1);
					}  // end if
				}  //  end for
			}  //  end while
			
			//  Output # occurrences of each letter in sorted print
			ArrayList <Character> keylist = new ArrayList<Character>(table.keySet());
			Collections.sort(keylist);
			for(char chr : keylist)
			{
				System.out.println(chr + ":" + table.get(chr));
			}
		}
	}

